<template>
  <div class="chat-image-uploader">
    <div class="image-upload-trigger" @click="triggerFileInput">
      <svg-icon name="common/image" />
      <span>图片</span>
    </div>
    <input 
      type="file" 
      ref="fileInput" 
      accept="image/*" 
      style="display: none" 
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import request from '@/utils/request';
import { useChatStore } from '@/stores/chat';

const props = defineProps({
  toUserId: {
    type: [Number, String],
    required: true
  }
});

const emit = defineEmits(['upload-success', 'upload-error']);
const fileInput = ref(null);
const chatStore = useChatStore();

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件选择变更
const handleFileChange = async (e) => {
  const file = e.target.files[0];
  if (!file) return;
  
  // 验证文件类型
  if (!file.type.includes('image/')) {
    ElMessage.error('请选择图片文件！');
    return;
  }
  
  // 验证文件大小（最大5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB！');
    return;
  }
  
  // 开始上传
  const loading = ElLoading.service({
    lock: true,
    text: '正在上传图片...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('toUserId', props.toUserId);
    formData.append('imageType', 'chat');
    
    const response = await request({
      url: '/chat/image/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (response.code === 200) {
      // 上传成功，添加图片消息到聊天记录
      const imageData = response.data;
      
      // 向聊天存储中添加消息
      chatStore.addImageMessage({
        toUserId: props.toUserId,
        imageUrl: imageData.imageUrl,
        messageId: imageData.messageId
      });
      
      // 触发上传成功事件
      emit('upload-success', imageData);
      ElMessage.success('图片发送成功');
    } else {
      throw new Error(response.msg || '图片发送失败');
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    ElMessage.error(error.message || '图片发送失败，请稍后重试');
    emit('upload-error', error);
  } finally {
    loading.close();
    // 清空文件输入，以便下次选择同一文件时也能触发change事件
    fileInput.value.value = '';
  }
};
</script>

<style lang="scss" scoped>
.chat-image-uploader {
  .image-upload-trigger {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 5px 10px;
    transition: all 0.3s;
    border-radius: 4px;
    
    &:hover {
      background-color: #f5f5f5;
    }
    
    .svg-icon {
      width: 20px;
      height: 20px;
      margin-right: 5px;
    }
    
    span {
      font-size: 14px;
    }
  }
}
</style> 